package com.itheima.springbootsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.springbootsecurity.domain.LoginUser;
import com.itheima.springbootsecurity.domain.User;
import com.itheima.springbootsecurity.exception.CustomAuthenticationException;
import com.itheima.springbootsecurity.mapper.UserMapper;
import com.itheima.springbootsecurity.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResourceService resourceService;

    /*
     * 根据用户名查询账号信息
     * @param username 用户名
     * @return 用户详细信息
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!StringUtils.hasLength(username)) {
            throw new InternalAuthenticationServiceException("用户名为空");
        }

        // 根据用户名查询账号信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);

        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 获取该用户可以访问的接口List
        List<String> authoritieList = resourceService.getPathListByUserid(user.getId());

//        if (Objects.isNull(user)) {
//            throw new RuntimeException("不存在此用户");
//        } else {
            return new LoginUser(user, authoritieList);
//        }
    }
}
